<template>
  <div style="height: calc(100vh - 60px); overflow-y: auto">
    <div style="height: 500px; background: #fff;margin-bottom:10px" v-if="showData">
      <v-chart autoresize class="chart" :option="option" @click="handlerClick" />
    </div>
    <div class="card">
      <div class="top-container">
        <el-input
          v-model="searchForm.title"
          class="iInput"
          size="small"
          placeholder="请输入文章标题"
          clearable
        />
        <el-select
          v-model="searchForm.type"
          placeholder="请选择分类"
          size="small"
          class="iInput"
          clearable
        >
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <el-select
          v-model="searchForm.model"
          placeholder="请选择类型"
          size="small"
          class="iInput"
          clearable
        >
          <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <el-date-picker
          v-model="searchForm.date"
          type="date"
          placeholder="请选择日期/时间"
          size="small"
          style="width: 120px; margin-right: 10px"
          :default-value="new Date(2010, 9, 1)"
        />
        <el-button icon="Search" size="small" @click="searchContent">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="reFlush" type="primary">刷新</el-button>
      </div>
      <div class="bottom-container">
        <div>
          <el-button size="small" type="danger" @click="deleteId(deleteIds, 1)">批量删除</el-button>
          <el-button size="small" type="success" @click="reExamine(deleteIds, 1)"
            >批量重审</el-button
          >
        </div>
        <el-pagination
          :hide-on-single-page="showPage"
          :page-size="pageItem.pageSize"
          :pager-count="pageItem.pageCount"
          layout="prev, pager, next"
          :total="pageItem.total"
          @change="changePage"
        />
      </div>
    </div>

    <div style="max-height: 430px; overflow-y: auto">
      <el-table
        ref="multipleTableRef"
        :data="blogList"
        style="width: 100%"
        height="430"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed />
        <el-table-column property="id" label="编号" width="80" />
        <el-table-column property="author" label="作者" show-overflow-tooltip />
        <el-table-column label="发布时间" show-overflow-tooltip>
          <template #default="scope">
            <div>
              {{ util.formatDateToYYYYMMDD(scope.row.createTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标题" show-overflow-tooltip>
          <template #default="scope">
            <div>
              {{ util.title(scope.row.title) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" show-overflow-tooltip width="100">
          <template #default="scope">
            <div>
              <el-tag size="small" :type="contenModel(scope.row.model)">{{
                util.model(scope.row.model)
              }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="typeName" label="分类" show-overflow-tooltip />
        <el-table-column label="状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.status === 2 ? 'success' : 'danger'" size="small">{{
              scope.row.status == 2 ? '已发布' : '未通过'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          show-overflow-tooltip
          fixed="right"
          width="220"
          align="center"
        >
          <template #default="scope">
            <el-button size="small" @click="deleteId(scope.row, 0)" type="primary">删除</el-button>
            <el-button size="small" @click="reExamine(scope.row.id, 0)" type="success"
              >重审</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <Statistics ref="statistics"></Statistics>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { ElMessage, ElTable, ElNotification } from 'element-plus'
import request from '@/util/request'
import util from '@/util/titleUtil'

// echarts
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'

import Statistics from '@/components/client/Statistics.vue'

use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent])

// table绑定
const multipleTableRef = ref()
// 批量删除的id
const deleteIds = ref([])
const showPage = ref(false)
const showData = ref(false)
const statistics = ref()
// 博客列表
const blogList = ref([])
// 分类列表
const typeList = ref([])
// 统计列表
const statisticalYear = ref([])
const statisticalData = ref([])
// 类型列表
const modelList = ref([
  { id: 0, name: '原创' },
  { id: 1, name: '转载' },
  { id: 2, name: '翻译' }
])

// 分页数据
const pageItem = ref({
  pageCount: null,
  pageSize: null,
  total: null,
  curentPage: 1
})
// 搜索表单
const searchForm = ref({
  title: '',
  type: null,
  model: null,
  date: null
})

const option = ref({
  title: {
    text: '年份发布统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '在{b}发布了 : {c}篇文章'
  },
  xAxis: {
    type: 'category',
    data: ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024']
    // data: statisticalYear.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '年份发布',
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      // data: statisticalData.value,
      type: 'line'
    }
  ]
})

// 监听选择
const handleSelectionChange = (ids) => {
  deleteIds.value = ids
  console.log('数组', deleteIds.value)
}

const getBlogList = () => {
  request
    .get(`/admin/content/list?page=${pageItem.value.curentPage}`)
    .then((res) => {
      console.log('获取的数据---', res)
      blogList.value = res.data.records
      pageItem.value.pageCount = res.data.pages
      pageItem.value.pageSize = res.data.size
      pageItem.value.total = res.data.total

      if (pageItem.value.pageCount <= 1) {
        showPage.value = true
      } else {
        showPage.value = false
      }
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        // ElMessage.error('出错了', err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const contenModel = (val) => {
  if (val === 0) {
    return 'error'
  } else if (val === 1) {
    return 'primary'
  } else if (val === 2) {
    return 'warning'
  }
}

// 监听statisticalYear和statisticalData的变化，并更新chartOption
watch(
  [statisticalYear, statisticalData],
  ([newYears, newData], [oldYears, oldData]) => {
    console.log('执行了')
    console.log('老数据', oldYears, oldData)
    console.log('新数据', newYears, newData)

    // 检查数组长度是否相等（仅作为安全检查）
    if (newYears.length === newData.length) {
      option.value.xAxis.data = newYears
      option.value.series[0].data = newData
      // 如果需要的话，您可以在这里触发图表的resize或其他更新逻辑
    }
  },
  { deep: true }
)

// 删除
const deleteId = (ids, type) => {
  var contentIds = []
  if (type === 1) {
    //批量删除
    contentIds = ids.map((obj) => {
      return obj.id
    })
  } else if (type === 0) {
    contentIds.push(ids.id)
  }
  console.log('---->', contentIds)

  if (contentIds.length <= 0 || contentIds === null) {
    ElMessage.warning('抱歉，不知道需要删除的数据是什么')
    return
  }

  request
    .post('/admin/content/delete', contentIds)
    .then((res) => {
      ElMessage.success('删除成功')
      getBlogList()
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        // ElMessage.error('出错了', err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
// 重审
const reExamine = (ids, type) => {
  var arr = []
  if (type === 1) {
    arr = ids.map((obj) => {
      return obj.id
    })
  } else if (type === 0) {
    arr.push(ids)
  }
  if (arr.length <= 0 || arr === null) {
    ElMessage.warning('抱歉，不知道需要重审那些数据')
    return
  }

  console.log(arr, ids, type)

  request
    .post('/admin/content/reexamine', arr)
    .then((res) => {
      ElMessage.success('重审成功')
      getBlogList()
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
// 搜索
const searchContent = () => {
  if (
    searchForm.value.date === null &&
    searchForm.value.model === null &&
    searchForm.value.type === null &&
    searchForm.value.title.trimEnd().trimStart() === ''
  ) {
    ElMessage.warning('搜索条件不能为空')
    return
  }

  console.log('1', searchForm.value.title.trim(), '2')

  request
    .post('/admin/content/search', searchForm.value)
    .then((res) => {
      console.log('获取的数据---', res)
      blogList.value = res.data.records
      pageItem.value.pageCount = res.data.pages
      pageItem.value.pageSize = res.data.size
      pageItem.value.total = res.data.total

      if (pageItem.value.pageCount <= 1) {
        showPage.value = true
      } else {
        showPage.value = false
      }
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const getStatistics = () => {
  request
    .get('/user/content/statistics')
    .then((res) => {
      console.log('统计数据', res)
      nextTick(() => {
        statisticalYear.value = res.data.map((item) => item.year)
        statisticalData.value = res.data.map((item) => item.count)
        showData.value = true
      }, 200)
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const changePage = (val) => {
  console.log('分页了', val)
  pageItem.value.curentPage = val
  getBlogList()
}

const getTypeList = () => {
  request
    .get('/admin/type/list')
    .then((res) => {
      console.log('获取成功：', res)
      typeList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const handlerClick = (a) => {
  console.log(a)
  console.log('发布年份', a.name)

  request
    .get(`/user/content/month?year=${a.name}`)
    .then((res) => {
      console.log('获取成功：', res)
      let month = res.data.map((item) => item.month)
      let data = res.data.map((item) => item.count)
      statistics.value.open(month, data)
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const reFlush = () => {
  searchForm.value = {
    title: '',
    date: null,
    type: null,
    model: null
  }
  getBlogList()
}

onMounted(() => {
  getBlogList()
  getTypeList()
  getStatistics()
})
</script>

<style scoped>
.card {
  display: flex;
  flex-direction: column;
  height: 70px; /* 根据需要设置卡片的高度 */
  width: 100%;
  background: #fff;
}

.top-container {
  display: flex;
  margin-bottom: 2px; /* 顶部容器和底部容器之间的间距 */
  padding: 5px;
}

.bottom-container {
  display: flex;
  padding: 5px;
  margin-top: auto; /* 将底部容器推至大容器的底部 */
  justify-content: space-between;
}

.iInput {
  margin-right: 10px; /* 根据需要设置输入框之间的间距 */
  width: 150px;
}

/* 最后一个输入框不需要右边距 */
/* .iInput:last-child {
  margin-right: 0;
} */
</style>
